import { createRouter, createWebHistory } from 'vue-router'
import { createRouteErrorHandler } from '@/utils/routeErrorHandler'
import { useAuthStore } from '@/stores/auth'

export const routes = [
    {
        path: '/',
        name: 'simple-home',
        component: () => import('@/views/SimpleHome.vue'),
        meta: { requiresAuth: false }
    },
    {
        path: '/development',
        name: 'development-index',
        component: () => import('@/views/DevelopmentIndex.vue'),
        meta: { requiresAuth: false }
    },
    // 登录页面路由
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/auth/Login.vue'),
        meta: { requiresAuth: false }
    },
    {
        path: '/toLogin',
        name: 'toLogin',
        component: () => import('@/views/auth/Login.vue'),
        meta: { requiresAuth: false }
    },
    //夜莺资产系统路由
    {
        path: '/main',
        component: () => import('@/components/layout/AppLayout.vue'),
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                name: 'home',
                component: () => import('@/views/teacher/Dashboard/TeacherDashboard.vue'),
                meta: { title:"首页", icon: 'icon-gf24-folder' }
            },
            {
                path: '/TeachingTasks',
                name: 'TeachingTasks',
                component: () => import('@/views/teacher/TeachingTasks/TaskList.vue'),
                meta: { title: "教学任务", icon: 'icon-fenxiang' }
            },
            {
                path: '/HomeworkReview',
                name: 'HomeworkReview',
                component: () => import('@/views/teacher/HomeworkReview/HomeworkReview.vue'),
                meta: { title: "批改作业", icon: 'icon-shanchu1' }
            },
            {
                path: '/StudentManagement',
                name: 'StudentManagement',
                component: () => import('@/views/teacher/StudentManagement/StudentList.vue'),
                meta: {
                    title:"学生档案",
                    icon: 'icon-gf24-folder'
                }
            },
            {
                path: '/Profile',
                name: 'Profile',
                component: () => import('@/views/teacher/Profile/PersonalCenter.vue'),
                meta: { title: '个人中心', icon: 'icon-gf24-folder' }
            },
            // 学生端页面
            {
                path: '/StudentDashboard',
                name: 'StudentDashboard',
                component: () => import('@/views/student/Dashboard/StudentDashboard.vue'),
                meta: { title: '学生端', icon: 'icon-gf24-folder' }
            },
            {
                path: '/LearningTasks',
                name: 'LearningTasks',
                component: () => import('@/views/student/LearningTasks/LearningTasks.vue'),
                meta: { title: '学习任务', icon: 'icon-fenxiang' }
            },
            {
                path: '/HomeworkSubmission',
                name: 'HomeworkSubmission',
                component: () => import('@/views/student/HomeworkSubmission/SubmissionForm.vue'),
                meta: { title: '作业提交', icon: 'icon-shanchu1' }
            }
        ]
    },
    // 教师端路由
    {
        path: '/teacher',
        name: 'teacher',
        component: () => import('@/components/shared/Layout/TeacherMainLayout.vue'),
        redirect: '/teacher/dashboard',
        meta: { requiresAuth: true },
        children: [
            {
                path: 'dashboard',
                name: 'teacher-dashboard',
                component: () => import('@/views/teacher/Dashboard/TeacherDashboard.vue'),
            },
            {
                path: 'teaching-tasks',
                name: 'teaching-tasks',
                component: () => import('@/views/teacher/TeachingTasks/TaskList.vue'),
            },
            {
                path: 'teaching-tasks/create',
                name: 'task-creation-wizard',
                component: () => import('@/components/shared/Wizards/TaskCreationWizard.vue'),
                props: () => ({ userType: 'teacher' })
            },
            {
                path: 'teaching-tasks/success',
                name: 'task-creation-success',
                component: () => import('@/views/teacher/TeachingTasks/TaskCreationSuccess.vue'),
            },
            {
                path: 'teaching-tasks/detail/:id',
                name: 'task-detail',
                component: () => import('@/views/teacher/TeachingTasks/TaskDetail.vue'),
            },
            {
                path: 'homework-review',
                name: 'homework-review',
                component: () => import('@/views/teacher/HomeworkReview/HomeworkReview.vue'),
            },
            {
                path: 'homework-review/history',
                name: 'grading-history',
                component: () => import('@/views/teacher/HomeworkReview/GradingHistory.vue'),
            },
            {
                path: 'homework-review/error-collection',
                name: 'teacher-error-collection',
                component: () => import('@/views/teacher/HomeworkReview/ErrorCollectionList.vue'),
            },
            {
                path: 'student-management',
                name: 'student-management',
                component: () => import('@/views/teacher/StudentManagement/StudentList.vue'),
            },
            {
                path: 'personal-center',
                name: 'personal-center',
                component: () => import('@/views/teacher/Profile/PersonalCenter.vue'),
            },
        ]
    },
    // 学生端路由
    {
        path: '/student',
        name: 'student',
        component: () => import('@/components/shared/Layout/StudentMainLayout.vue'),
        redirect: '/student/dashboard',
        meta: { requiresAuth: true },
        children: [
            {
                path: 'dashboard',
                name: 'student-dashboard',
                component: () => import('@/views/student/Dashboard/StudentDashboard.vue'),
            },
            {
                path: 'learning-tasks',
                name: 'student-learning-tasks',
                component: () => import('@/views/student/LearningTasks/LearningTasks.vue'),
            },
            {
                path: 'learning-tasks/create',
                name: 'create-learning-task',
                component: () => import('@/views/student/LearningTasks/CreateLearningTask.vue'),
            },
            {
                path: 'learning-tasks/list',
                name: 'student-task-list',
                component: () => import('@/views/student/LearningTasks/StudentTaskList.vue'),
            },
            {
                path: 'learning-tasks/wizard',
                name: 'student-task-creation-wizard',
                component: () => import('@/views/student/LearningTasks/StudentTaskCreationWizard.vue'),
            },
            {
                path: 'learning-tasks/success',
                name: 'student-task-creation-success',
                component: () => import('@/views/student/LearningTasks/StudentTaskCreationSuccess.vue'),
            },
            {
                path: 'learning-tasks/detail/:id',
                name: 'student-task-detail',
                component: () => import('@/views/student/LearningTasks/StudentTaskDetail.vue'),
            },
            {
                path: 'homework-submission',
                name: 'homework-submission',
                component: () => import('@/views/student/HomeworkSubmission/SubmissionForm.vue'),
            },
            {
                path: 'homework-review',
                name: 'student-homework-review',
                component: () => import('@/views/student/HomeworkReview/StudentHomeworkReview.vue'),
            },
            {
                path: 'homework-review/submission-history',
                name: 'student-submission-history',
                component: () => import('@/views/student/HomeworkReview/StudentSubmissionHistory.vue'),
            },
            {
                path: 'homework-review/error-collection',
                name: 'student-error-collection-list',
                component: () => import('@/views/student/HomeworkReview/StudentErrorCollectionList.vue'),
            },
            {
                path: 'profile',
                name: 'mycourse',
                component: () => import('@/views/student/HomeworkSubmission/MyCourses.vue'),
            },

            {
                path: 'profile/personal-center',
                name: 'student-personal-center',
                component: () => import('@/views/student/Profile/PersonalCenter.vue'),
            },
        ]
    },
    // 测试路由
    {
        path: '/test/camera',
        name: 'camera-test',
        component: () => import('@/views/test/CameraTest.vue'),
    },
    {
        path: '/test/language',
        name: 'language-test',
        component: () => import('@/views/test/LanguageTest.vue'),
    },
    // 独立页面路由（不使用MainLayout）- 按照文档规格要求
    {
        path: '/photo-preview',
        name: 'photo-preview',
        component: () => import('@/components/shared/Camera/PhotoPreview.vue'),
    },
    {
        path: '/camera-capture',
        name: 'camera-capture',
        component: () => import('@/components/shared/Camera/CameraCapture.vue'),
    },
    {
        path: '/homework-submission-detail/:taskId?',
        name: 'homework-submission-detail',
        component: () => import('@/components/shared/Views/HomeworkSubmissionDetail.vue'),
    },
    {
        path: '/error-collection/:taskId?',
        name: 'error-collection',
        component: () => import('@/components/shared/Common/ErrorCollection.vue'),
    },
    {
        path: '/wrong-question-collection/:collectionId?',
        name: 'wrong-question-collection',
        component: () => import('@/components/shared/Views/WrongQuestionCollection.vue'),
    },
    // 翻译测试页面
    {
        path: '/test-translation',
        name: 'test-translation',
        component: () => import('@/views/TestTranslation.vue'),
    },
    // 状态测试页面
    {
        path: '/status-test',
        name: 'status-test',
        component: () => import('@/views/StatusTest.vue'),
    },
    // 任务状态测试页面
    {
        path: '/task-status-test',
        name: 'task-status-test',
        component: () => import('@/views/TaskStatusTest.vue'),
    },
    // 日期选择器测试页面
    {
        path: '/date-picker-test',
        name: 'date-picker-test',
        component: () => import('@/views/DatePickerTest.vue'),
    },
    // 学生列表测试页面
    {
        path: '/student-list-test',
        name: 'student-list-test',
        component: () => import('@/views/StudentListTest.vue'),
    },
    // 分页同步测试页面
    {
        path: '/pagination-sync-test',
        name: 'pagination-sync-test',
        component: () => import('@/views/PaginationSyncTest.vue'),
    },
    // 路由测试页面
    {
        path: '/route-test',
        name: 'route-test',
        component: () => import('@/views/debug/RouteTest.vue'),
    },
    // 系统诊断页面
    {
        path: '/diagnostic',
        name: 'diagnostic',
        component: () => import('@/views/debug/DiagnosticPage.vue'),
    },
    // 翻译测试页面
    {
        path: '/translation-test',
        name: 'translation-test',
        component: () => import('@/views/debug/TranslationTest.vue'),
    },
    // 简单翻译测试页面
    {
        path: '/simple-translation-test',
        name: 'simple-translation-test',
        component: () => import('@/views/debug/SimpleTranslationTest.vue'),
    },
    // 网页图标测试页面
    {
        path: '/favicon-test',
        name: 'favicon-test',
        component: () => import('@/views/FaviconTest.vue'),
    },
    // 错误修复总结页面
    {
        path: '/error-fix-summary',
        name: 'error-fix-summary',
        component: () => import('@/views/ErrorFixSummary.vue'),
    },
    // 运行时错误调试页面
    {
        path: '/runtime-error-debug',
        name: 'runtime-error-debug',
        component: () => import('@/views/RuntimeErrorDebug.vue'),
    },
    // 空白页面修复总结
    {
        path: '/blank-page-fix',
        name: 'blank-page-fix',
        component: () => import('@/views/BlankPageFix.vue'),
    },
    // Sass 弃用警告修复
    {
        path: '/sass-deprecation-fix',
        name: 'sass-deprecation-fix',
        component: () => import('@/views/SassDeprecationFix.vue'),
    },
    // Sass 最终解决方案
    {
        path: '/sass-final-fix',
        name: 'sass-final-fix',
        component: () => import('@/views/SassFinalFix.vue'),
    },
    // 白屏问题解决方案
    {
        path: '/white-screen-fix',
        name: 'white-screen-fix',
        component: () => import('@/views/WhiteScreenFix.vue'),
    },
    // 404 页面
    {
        path: '/:pathMatch(.*)*',
        name: 'not-found',
        component: () => import('@/views/NotFound.vue'),
    },
]

// 创建路由器实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
// router.beforeEach((to, _from, next) => {
//   const authStore = useAuthStore()

//   // 不需要认证的路由
//   const publicRoutes = ['login', 'development-index', 'not-found']

//   // 如果是登录页面且已经登录，重定向到对应的首页
//   if (to.name === 'login' && authStore.isAuthenticated) {
//     if (authStore.userRole === 'teacher') {
//       next({ name: 'teacher-dashboard' })
//     } else if (authStore.userRole === 'student') {
//       next({ name: 'student-dashboard' })
//     } else {
//       next({ name: 'development-index' })
//     }
//     return
//   }

//   // 如果是其他公开路由，直接放行
//   if (publicRoutes.includes(to.name as string)) {
//     next()
//     return
//   }

//   // 检查是否需要认证
//   const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)

//   // 如果需要认证但未登录，跳转到登录页
//   if (requiresAuth && !authStore.isAuthenticated) {
//     next({ name: 'login' })
//     return
//   }

//   // 已登录或不需要认证，放行
//   next()
// })

// 添加路由守卫来设置默认语言和处理认证
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 在进入 /login 或 /toLogin 路由时设置默认语言为中文
  if (to.path === '/login' || to.path === '/toLogin') {
    try {
      // 动态导入语言设置函数
      const { setLanguage } = await import('@/plugins/i18nPlugin')
      const { useLocaleStore } = await import('@/stores/localeStore')

      // 设置默认语言为中文
      localStorage.setItem('i18nextLng', 'zh-CN')
      const localeStore = useLocaleStore()
      localeStore.setLocale('zh-CN')
      await setLanguage('zh-CN')

      console.log('路由守卫：已设置默认语言为中文')
    } catch (error) {
      console.error('路由守卫：设置语言失败', error)
    }
  }

  // 开发模式：允许直接访问所有页面
  if (import.meta.env.DEV) {
    next()
    return
  }

  // 检查是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)

  // 如果需要认证但未登录，跳转到登录页
  if (requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'login' })
    return
  }

  next()
})

// 初始化路由错误处理
const routeErrorHandler = createRouteErrorHandler(router)

// 导出路由器实例和错误处理器
export default router
export { routeErrorHandler }
